package com.test.platform.module.system.service;

import com.test.common.component.RedisComponent;
import com.test.common.entity.system.Token;
import com.test.platform.module.system.oauth2.TokenGenerator;
import com.test.common.repository.system.TokenRepository;
import com.test.common.response.BizException;
import com.test.common.response.ResultCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Service
public class TokenService {

    // 过期时间一星期
    private final static int EXPIRE = 3600 * 24 * 7;

    @Resource
    private TokenRepository tokenRepository;

    @Resource
    private RedisComponent redisCommonUtil;

    // 创建token
    public Token create(Integer userId) {

        // 生成一个token
        String token = TokenGenerator.generateValue();

        // 当前时间
        Date now = new Date();
        // 过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        // 存在则更新，不存在则创建（已实现多浏览器同时登录，共享token）
        Optional<Token> optional = tokenRepository.findById(userId);
        Token tokenEntity;
        if (optional.isPresent()) {

            tokenEntity = optional.get();
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
        } else {
            tokenEntity = new Token(userId, token, expireTime, now);
        }
        tokenEntity = tokenRepository.save(tokenEntity);
        // 更新缓存
        redisCommonUtil.set("shiro:token:" + token, tokenEntity, 60);
        return tokenEntity;
    }

    // 查询token
    public Token findByToken(String token) {

        Token tokenEntity = redisCommonUtil.get("shiro:token:" + token, Token.class);
        if (tokenEntity == null) {
            Optional<Token> optional = tokenRepository.findByToken(token);
            if (optional.isPresent()) {
                tokenEntity = optional.get();
                redisCommonUtil.set("shiro:token:" + token, tokenEntity, 60);
            } else {
                throw new BizException(ResultCode.USER_TOKEN_ERROR.code(), ResultCode.USER_TOKEN_ERROR.message());
            }
        }
        return tokenEntity;

    }

    // 根据用户ID查询token
    public Token findByUserId(Integer userId) {
        Optional<Token> optional = tokenRepository.findById(userId);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            throw new RuntimeException("找不到用户：" + userId);
        }
    }

    // 删除token
    public boolean delete(Integer userId) {
        Optional<Token> optional = tokenRepository.findById(userId);
        if (optional.isPresent()) {
            Token token = optional.get();
            // 删除redis中的token
            redisCommonUtil.delete("shiro:token:" + token.getToken());
            // 删除数据库中的token
            tokenRepository.deleteById(userId);
            return true;
        } else {
            return false;
        }
    }
}
